package com.integrationpath.mengine.webapp.servlet;

import com.integrationpath.mengine.model.Article;
import com.integrationpath.mengine.service.ArticleManager;
import com.integrationpath.mengine.service.impl.ArticleManagerImpl;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Sample Servlet that serves a feed created with ROME.
 * <p>
 * The feed type is determined by the 'type' request parameter, if the parameter is missing it defaults
 * to the 'default.feed.type' servlet init parameter, if the init parameter is missing it defaults to 'atom_0.3'
 * <p>
 */
public class FeedServletForNewsletter extends HttpServlet {
    private static final int RSS_LIMIT = 10;
	private static final String DEFAULT_FEED_TYPE = "default.feed.type";
    private static final String FEED_TYPE = "type";
    private static final String MIME_TYPE = "application/xml; charset=UTF-8";
    private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";

    private static final DateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd");

    private String _defaultFeedType;

    public void init() {
        _defaultFeedType = getServletConfig().getInitParameter(DEFAULT_FEED_TYPE);
        _defaultFeedType = (_defaultFeedType!=null) ? _defaultFeedType : "atom_0.3";
    }

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
        try {
            SyndFeed feed = getFeed(req);

            String feedType = req.getParameter(FEED_TYPE);
            feedType = (feedType!=null) ? feedType : _defaultFeedType;
            feed.setFeedType(feedType);

            res.setContentType(MIME_TYPE);
            SyndFeedOutput output = new SyndFeedOutput();
            output.output(feed,res.getWriter());
        }
        catch (FeedException ex) {
            String msg = COULD_NOT_GENERATE_FEED_ERROR;
            log(msg,ex);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
        }
    }

    protected SyndFeed getFeed(HttpServletRequest req) throws IOException,FeedException {
        SyndFeed feed = new SyndFeedImpl();
        
        ServletContext servletContext =this.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);        
          
        feed.setTitle("JAVA ROMANIA FEED");
        feed.setLink("http://www.javaromania.com");
        SyndImage syndImage = new SyndImageImpl();
        syndImage.setLink("http://javaromania.com");
        syndImage.setUrl("http://javaromania.com/mengine/images/logo.jpg");
        syndImage.setTitle("JAVA ROMANIA FEED");
        feed.setImage(syndImage);
        feed.setDescription("This is the feed for Java Romania Site. This site is dedicated to Java programmers from Romania and everywhere. Here you can read/publish articles, read/add news or entries from your blog... Please contribute to the comunity!!!");

        ArticleManager articleManager = (ArticleManager) wac.getBean("articleManagerNew");
        List articles = articleManager.getArticlesBySize(RSS_LIMIT);

        List<SyndEntry> entries = new ArrayList<SyndEntry>();
        SyndEntry entry;
        SyndContent description;
        Calendar rightNow = Calendar.getInstance();
        
        Calendar rssDate = Calendar.getInstance();
        
        for (Object object : articles) {
			Article article = (Article)object;
			entry = new SyndEntryImpl();
			entry.setTitle(article.getTitle());
			entry.setLink("http://javaromania.com/mengine/content_" + article.getTitle().trim().replace(' ', '-') + "_" + article.getId() + ".xhtml");
			entry.setPublishedDate(article.getDate());
			
			description = new SyndContentImpl();
			description.setType("text/plain");
			description.setValue(article.getOverview());
			entry.setDescription(description);
			
			rssDate.setTime(article.getDate());
			if(rightNow.get(Calendar.YEAR) == rssDate.get(Calendar.YEAR) &&
			   rightNow.get(Calendar.MONTH)-1 == rssDate.get(Calendar.MONTH)) {
	        entries.add(entry);
			}
		}

        feed.setEntries(entries);

        return feed;
    }

}
